package com.example.project.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.project.common.Result;
import com.example.project.dto.vo.admin.AdminMenuVO;
import com.example.project.dto.vo.admin.AdminPermVO;
import com.example.project.dto.vo.admin.AdminRoleVO;
import com.example.project.mapper.RoleMapper;
import com.example.project.mapper.AdminMenuMapper;
import com.example.project.mapper.AdminRoleMenuMapper;
import lombok.RequiredArgsConstructor;
import com.example.project.service.AdminRoleService;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/admin/role")
@RequiredArgsConstructor
public class AdminRoleController {

    private final RoleMapper roleMapper;
    private final AdminMenuMapper adminMenuMapper;
    private final AdminRoleMenuMapper adminRoleMenuMapper;
    private final AdminRoleService adminRoleService;

    @GetMapping
    public Result<List<AdminRoleVO>> listRoles() {
        return Result.ok(adminRoleService.list());
    }

    @GetMapping("/menu")
    public Result<List<AdminMenuVO>> listMenus() {
        return Result.ok(adminRoleService.listMenuTree());
    }

    @PutMapping("/menu")
    public Result<String> updateRoleMenus(@RequestParam("rid") Integer rid, @RequestBody Map<String, List<Integer>> req) {
        adminRoleService.updateRoleMenus(rid, req.getOrDefault("mids", Collections.emptyList()));
        return Result.ok("菜单已更新");
    }

    @GetMapping("/perm")
    public Result<List<AdminPermVO>> listPerms() {
        AdminPermVO p = new AdminPermVO();
        p.setId(1);
        p.setName("USER_MANAGE");
        p.setDesc_("用户管理");
        p.setUrl("/admin/user");
        return Result.ok(Collections.singletonList(p));
    }

    @PostMapping
    public Result<String> createRole(@RequestBody AdminRoleVO payload) {
        adminRoleService.addOrUpdate(payload);
        return Result.ok("创建成功");
    }

    @PutMapping
    public Result<String> updateRole(@RequestBody AdminRoleVO payload) {
        adminRoleService.addOrUpdate(payload);
        return Result.ok("修改成功");
    }

    @PutMapping("/status")
    public Result<String> updateStatus(@RequestBody Map<String, Object> body) {
        Integer rid = (Integer) body.get("id");
        Boolean enabled = (Boolean) body.get("enabled");
        adminRoleService.updateRoleStatus(rid, enabled != null && enabled);
        return Result.ok("状态已更新");
    }
}


